'use client';

import { useState, useEffect, useRef, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  Search,
  FileText,
  Clock,
  Tag,
  ArrowRight,
  Loader2,
} from 'lucide-react';
import { Doc } from '@/lib/docs';

interface SearchResult {
  doc: Doc;
  score: number;
  matchedContent: string;
}

interface DocsSearchProps {
  docs: Doc[];
  className?: string;
}

/**
 * 文档搜索组件
 * 提供实时搜索和结果展示功能
 */
export function DocsSearch({ docs, className }: DocsSearchProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [query, setQuery] = useState('');
  const [results, setResults] = useState<SearchResult[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [selectedIndex, setSelectedIndex] = useState(0);
  const inputRef = useRef<HTMLInputElement>(null);
  const router = useRouter();

  // 键盘快捷键
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
        e.preventDefault();
        setIsOpen(true);
      }

      if (e.key === 'Escape') {
        setIsOpen(false);
      }
    };

    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, []);

  /**
   * 执行搜索
   */
  const performSearch = useCallback(
    (searchQuery: string, allDocs: Doc[]): SearchResult[] => {
      const lowercaseQuery = searchQuery.toLowerCase();
      const words = lowercaseQuery.split(' ').filter(word => word.length > 0);

      const searchResults: SearchResult[] = [];

      allDocs.forEach(doc => {
        let score = 0;
        let matchedContent = '';

        // 搜索标题（权重最高）
        const titleMatches = words.filter(word =>
          doc.meta.title.toLowerCase().includes(word)
        ).length;
        score += titleMatches * 10;

        // 搜索描述
        const descMatches = words.filter(word =>
          doc.meta.description.toLowerCase().includes(word)
        ).length;
        score += descMatches * 5;

        // 搜索标签
        const tagMatches = words.filter(word =>
          (doc.meta.tags || []).some(tag => tag.toLowerCase().includes(word))
        ).length;
        score += tagMatches * 3;

        // 搜索内容
        const contentText = doc.content.toLowerCase();
        const contentMatches = words.filter(word =>
          contentText.includes(word)
        ).length;
        score += contentMatches * 1;

        // 提取匹配的内容片段
        if (score > 0) {
          matchedContent = extractMatchedContent(doc.content, words);
          searchResults.push({ doc, score, matchedContent });
        }
      });

      // 按分数排序
      return searchResults.sort((a, b) => b.score - a.score).slice(0, 10); // 限制结果数量
    },
    []
  );

  // 搜索逻辑
  useEffect(() => {
    if (!query.trim()) {
      setResults([]);
      return;
    }

    setIsLoading(true);

    // 模拟搜索延迟
    const searchTimeout = setTimeout(() => {
      const searchResults = performSearch(query, docs);
      setResults(searchResults);
      setSelectedIndex(0);
      setIsLoading(false);
    }, 200);

    return () => clearTimeout(searchTimeout);
  }, [query, docs, performSearch]);

  /**
   * 提取匹配的内容片段
   */
  const extractMatchedContent = (content: string, words: string[]): string => {
    const sentences = content.split(/[.!?]\s+/);

    for (const sentence of sentences) {
      const lowerSentence = sentence.toLowerCase();
      if (words.some(word => lowerSentence.includes(word))) {
        return sentence.trim().substring(0, 150) + '...';
      }
    }

    return content.substring(0, 150) + '...';
  };

  /**
   * 处理结果点击
   */
  const handleResultClick = useCallback(
    (doc: Doc) => {
      router.push(`/docs/${doc.slug}`);
      setIsOpen(false);
      setQuery('');
    },
    [router]
  );

  // 键盘导航
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (!isOpen) return;

      switch (e.key) {
        case 'ArrowDown':
          e.preventDefault();
          setSelectedIndex(prev =>
            prev < results.length - 1 ? prev + 1 : prev
          );
          break;
        case 'ArrowUp':
          e.preventDefault();
          setSelectedIndex(prev => (prev > 0 ? prev - 1 : prev));
          break;
        case 'Enter':
          e.preventDefault();
          if (results[selectedIndex]) {
            handleResultClick(results[selectedIndex].doc);
          }
          break;
      }
    };

    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, [isOpen, results, selectedIndex, handleResultClick]);

  /**
   * 高亮匹配文本
   */
  const highlightText = (text: string, query: string) => {
    if (!query.trim()) return text;

    const words = query
      .toLowerCase()
      .split(' ')
      .filter(word => word.length > 0);
    let highlightedText = text;

    words.forEach(word => {
      const regex = new RegExp(`(${word})`, 'gi');
      highlightedText = highlightedText.replace(
        regex,
        '<mark class="bg-yellow-200 dark:bg-yellow-800">$1</mark>'
      );
    });

    return highlightedText;
  };

  /**
   * 获取难度颜色
   */
  const getDifficultyColor = (difficulty?: string) => {
    switch (difficulty) {
      case 'beginner':
        return 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300';
      case 'intermediate':
        return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-300';
      case 'advanced':
        return 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-300';
      default:
        return 'bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-300';
    }
  };

  return (
    <>
      {/* 搜索触发按钮 */}
      <Button
        variant="outline"
        className={cn(
          'relative h-9 w-full justify-start text-sm text-muted-foreground sm:pr-12 md:w-40 lg:w-64',
          className
        )}
        onClick={() => setIsOpen(true)}
      >
        <Search className="mr-2 h-4 w-4" />
        <span className="hidden lg:inline-flex">搜索文档...</span>
        <span className="inline-flex lg:hidden">搜索...</span>
        <kbd className="pointer-events-none absolute right-1.5 top-1.5 hidden h-5 select-none items-center gap-1 rounded border bg-muted px-1.5 font-mono text-[10px] font-medium opacity-100 sm:flex">
          <span className="text-xs">⌘</span>K
        </kbd>
      </Button>

      {/* 搜索对话框 */}
      <Dialog open={isOpen} onOpenChange={setIsOpen}>
        <DialogContent className="max-w-2xl p-0">
          <DialogHeader className="px-4 py-3 border-b">
            <DialogTitle className="sr-only">搜索文档</DialogTitle>
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              <Input
                ref={inputRef}
                placeholder="搜索文档..."
                value={query}
                onChange={e => setQuery(e.target.value)}
                className="pl-10 border-0 focus-visible:ring-0 focus-visible:ring-offset-0"
                autoFocus
              />
              {isLoading && (
                <Loader2 className="absolute right-3 top-1/2 transform -translate-y-1/2 h-4 w-4 animate-spin text-muted-foreground" />
              )}
            </div>
          </DialogHeader>

          <div className="max-h-96 overflow-y-auto">
            {query.trim() === '' ? (
              // 空状态 - 显示提示
              <div className="p-8 text-center text-muted-foreground">
                <Search className="mx-auto h-12 w-12 mb-4 opacity-50" />
                <p className="text-lg font-medium mb-2">搜索文档</p>
                <p className="text-sm">输入关键词搜索相关文档</p>
                <div className="flex items-center justify-center gap-2 mt-4 text-xs">
                  <kbd className="px-2 py-1 bg-muted rounded text-muted-foreground">
                    ↑↓
                  </kbd>
                  <span>导航</span>
                  <kbd className="px-2 py-1 bg-muted rounded text-muted-foreground">
                    Enter
                  </kbd>
                  <span>选择</span>
                  <kbd className="px-2 py-1 bg-muted rounded text-muted-foreground">
                    Esc
                  </kbd>
                  <span>关闭</span>
                </div>
              </div>
            ) : results.length === 0 && !isLoading ? (
              // 无结果状态
              <div className="p-8 text-center text-muted-foreground">
                <FileText className="mx-auto h-12 w-12 mb-4 opacity-50" />
                <p className="text-lg font-medium mb-2">未找到相关文档</p>
                <p className="text-sm">尝试使用不同的关键词搜索</p>
              </div>
            ) : (
              // 搜索结果
              <div className="py-2">
                {results.map((result, index) => (
                  <button
                    key={result.doc.slug}
                    className={cn(
                      'w-full px-4 py-3 text-left hover:bg-muted/50 transition-colors border-l-2 border-transparent',
                      index === selectedIndex && 'bg-muted border-l-primary'
                    )}
                    onClick={() => handleResultClick(result.doc)}
                  >
                    <div className="flex items-start justify-between gap-3">
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2 mb-1">
                          <FileText className="h-4 w-4 text-muted-foreground flex-shrink-0" />
                          <h3
                            className="font-medium text-sm truncate"
                            dangerouslySetInnerHTML={{
                              __html: highlightText(
                                result.doc.meta.title,
                                query
                              ),
                            }}
                          />
                          {result.doc.meta.difficulty && (
                            <Badge
                              className={cn(
                                'text-xs',
                                getDifficultyColor(result.doc.meta.difficulty)
                              )}
                            >
                              {result.doc.meta.difficulty}
                            </Badge>
                          )}
                        </div>

                        <p
                          className="text-xs text-muted-foreground line-clamp-2 mb-2"
                          dangerouslySetInnerHTML={{
                            __html: highlightText(result.matchedContent, query),
                          }}
                        />

                        <div className="flex items-center gap-3 text-xs text-muted-foreground">
                          <Badge variant="outline" className="text-xs">
                            {result.doc.meta.category}
                          </Badge>

                          <div className="flex items-center gap-1">
                            <Clock className="h-3 w-3" />
                            <span>{result.doc.readingTime.text}</span>
                          </div>

                          {result.doc.meta.tags &&
                            result.doc.meta.tags.length > 0 && (
                              <div className="flex items-center gap-1">
                                <Tag className="h-3 w-3" />
                                <span>
                                  {result.doc.meta.tags.slice(0, 2).join(', ')}
                                </span>
                                {result.doc.meta.tags.length > 2 && (
                                  <span>
                                    +{result.doc.meta.tags.length - 2}
                                  </span>
                                )}
                              </div>
                            )}
                        </div>
                      </div>

                      <ArrowRight className="h-4 w-4 text-muted-foreground flex-shrink-0" />
                    </div>
                  </button>
                ))}
              </div>
            )}
          </div>

          {results.length > 0 && (
            <div className="px-4 py-2 border-t bg-muted/30 text-xs text-muted-foreground">
              找到 {results.length} 个结果
            </div>
          )}
        </DialogContent>
      </Dialog>
    </>
  );
}

/**
 * 简化的搜索输入框
 * 用于侧边栏等空间受限的地方
 */
interface SimpleSearchProps {
  onSearch: (query: string) => void;
  placeholder?: string;
  className?: string;
}

export function SimpleSearch({
  onSearch,
  placeholder = '搜索...',
  className,
}: SimpleSearchProps) {
  const [query, setQuery] = useState('');

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setQuery(value);
    onSearch(value);
  };

  return (
    <div className={cn('relative', className)}>
      <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
      <Input
        placeholder={placeholder}
        value={query}
        onChange={handleChange}
        className="pl-10"
      />
    </div>
  );
}
